package com.neusoft.hifly.commons.web;

import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import javax.net.ssl.SSLException;

import org.apache.commons.codec.Charsets;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.config.SocketConfig;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;

/**
 * 使用HttpClient发送和接收Http请求
 */
public class HttpUtil {

	private static HttpClient httpClient;
	// 最大连接数
	private static final int MAX_CONNECTION = 100;
	// 每个route能使用的最大连接数，一般和MAX_CONNECTION取值一样
	private static final int MAX_CONCURRENT_CONNECTIONS = 100;
	// 建立连接的超时时间，单位毫秒
	private static final int CONNECTION_TIME_OUT = 3000;
	// 请求超时时间，单位毫秒
	private static final int REQUEST_TIME_OUT = 3000;
	// 最大失败重试次数
	private static final int MAX_FAIL_RETRY_COUNT = 3;
	// 请求编码
	private static final String REQUEST_ENCODING = "UTF-8";
	// 请求配置，可以复用
	private static RequestConfig requestConfig;

	static {
		final SocketConfig socketConfig = SocketConfig.custom().setSoTimeout(HttpUtil.REQUEST_TIME_OUT)
				.setSoKeepAlive(true).setTcpNoDelay(true).build();

		HttpUtil.requestConfig = RequestConfig.custom().setSocketTimeout(HttpUtil.REQUEST_TIME_OUT)
				.setConnectTimeout(HttpUtil.CONNECTION_TIME_OUT).build();
		/**
		 * 每个默认的 ClientConnectionPoolManager 实现将给每个route创建不超过2个并发连接，最多20个连接总数。
		 */
		final PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
		connManager.setMaxTotal(HttpUtil.MAX_CONNECTION);
		connManager.setDefaultMaxPerRoute(HttpUtil.MAX_CONCURRENT_CONNECTIONS);
		connManager.setDefaultSocketConfig(socketConfig);

		HttpUtil.httpClient = HttpClients.custom().setConnectionManager(connManager)
				// 添加重试处理器
				.setRetryHandler(new MyHttpRequestRetryHandler()).build();
	}

	public static void main(final String[] args) {
		HttpUtil.testGet();
	}

	/**
	 * 测试get方法
	 */
	private static void testGet() {
		final String url = "http://restapi.amap.com/v3/place/text";
		final Map<String, String> paramMap = new HashMap<String, String>();
		paramMap.put("key", "95708f902ac2428ea119ec99fb70e6a3");
		paramMap.put("keywords", "互联网金融大厦");
		paramMap.put("city", "330100");
		paramMap.put("extensions", "all");

		try {
			System.out.println(HttpUtil.get(url, paramMap));

		} catch (final Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * post请求
	 *
	 * @param url
	 *            请求地址
	 * @param paramMap
	 *            参数
	 * @param headers
	 *            头信息
	 * @return 返回值
	 * @throws Exception
	 *             异常
	 */
	public static String post(final String url, final Map<String, String> paramMap, final Map<String, String> headers)
			throws Exception {
		final URIBuilder uriBuilder = new URIBuilder(url);
		if (paramMap != null) {
			// 添加请求参数
			for (final Entry<String, String> entry : paramMap.entrySet()) {
				uriBuilder.addParameter(entry.getKey(), URLEncoder.encode(entry.getValue(), HttpUtil.REQUEST_ENCODING));
			}
		}

		final HttpPost httpPost = new HttpPost(uriBuilder.build());
		if (headers != null) {
			// 添加请求首部
			for (final Entry<String, String> header : headers.entrySet()) {
				httpPost.addHeader(header.getKey(), header.getValue());
			}
		}

		httpPost.setConfig(HttpUtil.requestConfig);

		// 执行请求
		final HttpResponse response = HttpUtil.httpClient.execute(httpPost);

		return EntityUtils.toString(response.getEntity(), Charsets.UTF_8);
	}

	/**
	 * post请求，不带请求首部
	 *
	 * @param url
	 *            请求地址
	 * @param paramMap
	 *            参数
	 * @return 返回值
	 * @throws Exception
	 *             异常
	 */
	public static String post(final String url, final Map<String, String> paramMap) throws Exception {
		return HttpUtil.post(url, paramMap, null);
	}

	/**
	 * post请求，不带请求首部
	 *
	 * @param url
	 *            请求地址
	 * @return 返回值
	 * @throws Exception
	 *             异常
	 */
	public static String post(final String url) throws Exception {
		return HttpUtil.post(url, null, null);
	}

	/**
	 * post请求，不带请求首部，参数是JSON
	 *
	 * @param url
	 *            请求地址
	 * @param paramJson
	 *            JSON参数
	 * @return 返回值
	 * @throws Exception
	 *             异常
	 */
	public static String post(final String url, final String paramJson) throws Exception {
		final URIBuilder uriBuilder = new URIBuilder(url);

		final HttpPost httpPost = new HttpPost(uriBuilder.build());

		if (StringUtils.isNotEmpty(paramJson)) {
			//装填参数
			final StringEntity s = new StringEntity(paramJson, HttpUtil.REQUEST_ENCODING);
			s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
			//设置参数到请求对象中
			httpPost.setEntity(s);
		}

		httpPost.setConfig(HttpUtil.requestConfig);

		// 执行请求
		final HttpResponse response = HttpUtil.httpClient.execute(httpPost);

		return EntityUtils.toString(response.getEntity(), Charsets.UTF_8);
	}

	/**
	 * get请求
	 *
	 * @param url
	 *            请求地址
	 * @param paramMap
	 *            参数
	 * @param headers
	 *            头信息
	 * @return 返回值
	 * @throws Exception
	 *             异常
	 */
	public static String get(final String url, final Map<String, String> paramMap, final Map<String, String> headers)
			throws Exception {
		final URIBuilder uriBuilder = new URIBuilder(url);
		if (paramMap != null) {
			// 添加请求参数
			for (final Entry<String, String> entry : paramMap.entrySet()) {
				uriBuilder.addParameter(entry.getKey(), URLEncoder.encode(entry.getValue(), HttpUtil.REQUEST_ENCODING));
			}
		}

		final HttpGet httpGet = new HttpGet(uriBuilder.build());
		if (headers != null) {
			// 添加请求首部
			for (final Entry<String, String> header : headers.entrySet()) {
				httpGet.addHeader(header.getKey(), header.getValue());
			}
		}

		httpGet.setConfig(HttpUtil.requestConfig);

		// 执行请求
		final HttpResponse response = HttpUtil.httpClient.execute(httpGet);

		return EntityUtils.toString(response.getEntity(), Charsets.UTF_8);
	}

	/**
	 * get请求，不带请求首部
	 *
	 * @param url
	 *            请求地址
	 * @param paramMap
	 *            参数
	 * @return 返回值
	 * @throws Exception
	 *             异常
	 */
	public static String get(final String url, final Map<String, String> paramMap) throws Exception {
		return HttpUtil.get(url, paramMap, null);
	}

	/**
	 * get请求，不带请求首部
	 *
	 * @param url
	 *            请求地址
	 * @return 返回值
	 * @throws Exception
	 *             异常
	 */
	public static String get(final String url) throws Exception {
		return HttpUtil.get(url, null, null);
	}

	/**
	 * put请求
	 *
	 * @param url
	 *            请求地址
	 * @return 返回值
	 * @throws Exception
	 *             异常
	 */
	public static String put(final String url) throws Exception {
		final URIBuilder uriBuilder = new URIBuilder(url);

		final HttpPut httpPut = new HttpPut(uriBuilder.build());

		httpPut.setConfig(HttpUtil.requestConfig);

		// 执行请求
		final HttpResponse response = HttpUtil.httpClient.execute(httpPut);

		return EntityUtils.toString(response.getEntity(), Charsets.UTF_8);
	}

	/**
	 * 请求重试处理器
	 */
	private static class MyHttpRequestRetryHandler implements HttpRequestRetryHandler {

		@Override
		public boolean retryRequest(final IOException exception, final int executionCount, final HttpContext context) {
			if (executionCount >= HttpUtil.MAX_FAIL_RETRY_COUNT) {
				return false;
			}

			if (exception instanceof InterruptedIOException) {
				// 超时
				return false;
			} else if (exception instanceof UnknownHostException) {
				// 未知主机
				return false;
			} else if (exception instanceof ConnectTimeoutException) {
				// 连接被拒绝
				return false;
			} else if (exception instanceof SSLException) {
				// SSL handshake exception
				return false;
			}

			final HttpClientContext clientContext = HttpClientContext.adapt(context);
			final HttpRequest request = clientContext.getRequest();
			final boolean idempotent = !(request instanceof HttpEntityEnclosingRequest);
			if (idempotent) {
				// 如果请求被认为是幂等的，则重试
				return true;
			}

			return false;
		}
	}
}